import { createApp } from 'vue'
import CustomMessage from '@/components/CustomMessage.vue'
import ElementPlus from 'element-plus'

let messageInstance = null
let messageContainer = null

const createMessageContainer = () => {
  if (!messageContainer) {
    messageContainer = document.createElement('div')
    messageContainer.id = 'custom-message-container'
    document.body.appendChild(messageContainer)
  }
  return messageContainer
}

const showMessage = (options) => {
  // 如果已有消息实例，先关闭它
  if (messageInstance) {
    messageInstance.unmount()
    messageInstance = null
  }

  const container = createMessageContainer()
  
  // 创建新的消息实例
  messageInstance = createApp(CustomMessage, {
    ...options,
    onClose: () => {
      if (messageInstance) {
        messageInstance.unmount()
        messageInstance = null
      }
    }
  })
  
  messageInstance.use(ElementPlus)
  messageInstance.mount(container)
}

const Message = {
  success: (message, duration = 3000) => {
    showMessage({ message, type: 'success', duration })
  },
  warning: (message, duration = 3000) => {
    showMessage({ message, type: 'warning', duration })
  },
  error: (message, duration = 3000) => {
    showMessage({ message, type: 'error', duration })
  },
  info: (message, duration = 3000) => {
    showMessage({ message, type: 'info', duration })
  }
}

export default Message